import { useUserStore } from '@/stores/user'

// 权限指令
export const permission = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const roles = userStore.roles
    const permissions = userStore.permissions

    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value

      const hasPermission = roles.some(role => {
        return permissionRoles.includes(role)
      })

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('需要指定权限角色! 如 v-permission="[\'admin\',\'user\']"')
    }
  }
}

// 权限检查指令（基于权限码）
export const hasPermission = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const permissions = userStore.permissions

    if (value && typeof value === 'string') {
      const hasPermission = permissions.includes(value) || permissions.includes('*:*:*')

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('需要指定权限码! 如 v-has-permission="\'user:add\'"')
    }
  }
}

// 角色检查指令
export const hasRole = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const roles = userStore.roles

    if (value && typeof value === 'string') {
      const hasRole = roles.includes(value)

      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else if (value && value instanceof Array && value.length > 0) {
      const hasRole = roles.some(role => value.includes(role))

      if (!hasRole) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('需要指定角色! 如 v-has-role="\'admin\'" 或 v-has-role="[\'admin\', \'user\']"')
    }
  }
}
